package com.zscat.mallplus.center.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zscat.mallplus.active.service.ISysStoreService;
import com.zscat.mallplus.center.service.ICenterOrderService;
import com.zscat.mallplus.enums.AllEnum.OrderSource;
import com.zscat.mallplus.enums.AllEnum.OrderType;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.oms.entity.OmsOrder;
import com.zscat.mallplus.oms.entity.OmsOrderItem;
import com.zscat.mallplus.oms.entity.OmsOrderOperateHistory;
import com.zscat.mallplus.oms.entity.OmsOrderSetting;
import com.zscat.mallplus.oms.mapper.OmsOrderSettingMapper;
import com.zscat.mallplus.oms.service.IOmsOrderItemService;
import com.zscat.mallplus.oms.service.IOmsOrderOperateHistoryService;
import com.zscat.mallplus.oms.service.IOmsOrderService;
import com.zscat.mallplus.oms.vo.ConfirmOrderResult;
import com.zscat.mallplus.oms.vo.OrderParam;
import com.zscat.mallplus.pms.entity.PmsFeightTemplate;
import com.zscat.mallplus.pms.entity.PmsProduct;
import com.zscat.mallplus.pms.entity.PmsSkuStock;
import com.zscat.mallplus.pms.service.IPmsFeightTemplateService;
import com.zscat.mallplus.pms.service.IPmsProductService;
import com.zscat.mallplus.pms.service.IPmsSkuStockService;
import com.zscat.mallplus.sms.entity.SmsCoupon;
import com.zscat.mallplus.sms.entity.SmsCouponHistory;
import com.zscat.mallplus.sms.entity.SmsFlashPromotion;
import com.zscat.mallplus.sms.entity.SmsFlashPromotionProductRelation;
import com.zscat.mallplus.sms.entity.SmsFlashPromotionSession;
import com.zscat.mallplus.sms.entity.SmsGroup;
import com.zscat.mallplus.sms.entity.SmsGroupMember;
import com.zscat.mallplus.sms.entity.SmsGroupRecord;
import com.zscat.mallplus.sms.mapper.SmsCouponHistoryMapper;
import com.zscat.mallplus.sms.mapper.SmsGroupMemberMapper;
import com.zscat.mallplus.sms.mapper.SmsGroupRecordMapper;
import com.zscat.mallplus.sms.service.ISmsCouponHistoryService;
import com.zscat.mallplus.sms.service.ISmsCouponService;
import com.zscat.mallplus.sms.service.ISmsFlashPromotionProductRelationService;
import com.zscat.mallplus.sms.service.ISmsFlashPromotionService;
import com.zscat.mallplus.sms.service.ISmsFlashPromotionSessionService;
import com.zscat.mallplus.sms.service.ISmsGroupService;
import com.zscat.mallplus.sys.entity.SysStore;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.entity.UmsMemberReceiveAddress;
import com.zscat.mallplus.ums.mapper.UmsIntegrationConsumeSettingMapper;
import com.zscat.mallplus.ums.service.IUmsMemberReceiveAddressService;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ValidatorUtils;

@Service
public class CenterOrderServiceImpl implements ICenterOrderService {
	@Resource
	private IUmsMemberService memberService;
	@Resource
	private ISysStoreService storeService;
	@Resource
	private IUmsMemberReceiveAddressService addressService;
	@Resource
	private ISmsCouponService couponService;
	@Resource
	private ISmsCouponHistoryService couponHistoryService;
	@Resource
	private OmsOrderSettingMapper orderSettingMapper;
	@Resource
	private IPmsProductService productService;
	@Resource
	private IOmsOrderService orderService;
	@Resource
	private IPmsSkuStockService skuStockService;
	@Resource
	private IOmsOrderItemService orderItemService;
	@Autowired
	private IOmsOrderOperateHistoryService orderOperateHistoryService;
	@Autowired
	private SmsGroupRecordMapper groupRecordMapper;
	@Autowired
	private ISmsGroupService groupService;
	@Autowired
	private SmsGroupMemberMapper groupMemberMapper;
	@Resource
	private UmsIntegrationConsumeSettingMapper integrationConsumeSettingMapper;
	@Autowired
	private ISmsFlashPromotionProductRelationService flashPromotionProductRelationService;
	@Autowired
	private SmsCouponHistoryMapper couponHistoryMapper;
	@Autowired
	private IPmsFeightTemplateService feightTemplateService;
	@Autowired
	private ISmsFlashPromotionService flashPromotionService;
	@Autowired
	private ISmsFlashPromotionSessionService flashPromotionSessionService;

	@Override
	public Object confirmOrderResult(OrderParam orderParam) {
		UmsMember currentMember = memberService.getNewCurrentMember();
		if (null == currentMember) {
			return new CommonResult().failed("请先登录");
		}
		SysStore store = storeService.getById(orderParam.getShopId());
		if (null == store) {
			return new CommonResult().failed("科技馆编号有误");
		}
		ConfirmOrderResult result = new ConfirmOrderResult();
		result.setStoreId(store.getId());
		result.setStoreName(store.getName());
		// 获取用户收货地址列表
		UmsMemberReceiveAddress entity = new UmsMemberReceiveAddress();
		entity.setMemberId(currentMember.getId());
		List<UmsMemberReceiveAddress> memberReceiveAddressList = addressService.list(new QueryWrapper<>(entity));
		result.setMemberReceiveAddressList(memberReceiveAddressList);
		entity.setDefaultStatus(1);
		UmsMemberReceiveAddress address = addressService.getOne(new QueryWrapper<UmsMemberReceiveAddress>(entity));
		result.setAddress(address);
		// 获取用户可用优惠券列表
		result.setCouponHistoryDetailList(
				couponHistoryMapper.getDetailList(currentMember.getId(), orderParam.getShopId()));
		// 获取用户余额
		UmsMember member = memberService.getById(currentMember.getId());
		result.setBlance(member.getBlance());
		PmsProduct product = productService.getById(orderParam.getGoodsId());
		result.setGoods(product);
		// 根据商品设置的运费模板ID查询运费模板详情
		BigDecimal freightAmount = BigDecimal.ZERO;
		BigDecimal total = BigDecimal.valueOf(orderParam.getTotal());// 数量
		freightAmount = calcFeightAmount(freightAmount, total, product);
		// 计算总金额、活动优惠、应付金额
		BigDecimal totalAmount = BigDecimal.ZERO;
		BigDecimal promotionAmount = BigDecimal.ZERO;
		BigDecimal payAmount = BigDecimal.ZERO;
		if (null != orderParam.getCouponId()) {
			SmsCoupon coupon = couponService.getById(orderParam.getCouponId());
			promotionAmount = coupon.getAmount();
		}
		if (orderParam.getOrderType() == 1) {// 订单类型：1->普通订单；2->秒杀订单；3->拼团订单；4->积分订单
			totalAmount = product.getPrice().multiply(total);
		} else if (orderParam.getOrderType() == 2) {
			SmsFlashPromotionProductRelation flashPromotionProductRelation = flashPromotionProductRelationService
					.getById(orderParam.getSkillId());
			totalAmount = flashPromotionProductRelation.getFlashPromotionPrice().multiply(total);
		} else if (orderParam.getOrderType() == 3) {
			SmsGroup group = groupService.getById(orderParam.getGroupId());
			totalAmount = group.getGroupPrice().multiply(total);
		}
		payAmount = totalAmount.subtract(freightAmount).subtract(promotionAmount);
		ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
		calcAmount.setFreightAmount(freightAmount);
		calcAmount.setPayAmount(payAmount);
		calcAmount.setPromotionAmount(promotionAmount);
		calcAmount.setTotalAmount(totalAmount);
		result.setCalcAmount(calcAmount);
		return new CommonResult().success(result);
	}

	private BigDecimal calcFeightAmount(BigDecimal freightAmount, BigDecimal total, PmsProduct product) {
		PmsFeightTemplate feightTemplate = feightTemplateService.getById(product.getFeightTemplateId());
		if (null != feightTemplate) {
			// 按重量计算
			if (feightTemplate.getChargeType() == 0) {
				BigDecimal weight = product.getWeight().multiply(total);
				if (feightTemplate.getFirstWeight().compareTo(weight) <= 0) {
					freightAmount = feightTemplate.getFirstFee();
				} else {
					freightAmount = feightTemplate.getFirstFee().add((weight.subtract(feightTemplate.getFirstWeight()))
							.multiply(feightTemplate.getContinmeFee()));
				}
			}
			// 按件数计算
			if (feightTemplate.getChargeType() == 1) {
				if (feightTemplate.getFirstWeight().compareTo(total) <= 0) {
					freightAmount = feightTemplate.getFirstFee();
				} else {
					freightAmount = feightTemplate.getFirstFee().add((total.subtract(feightTemplate.getFirstWeight()))
							.multiply(feightTemplate.getContinmeFee()));
				}
			}
		}
		return freightAmount;
	}

	@Override
	public Object submitGroupOrder(OrderParam orderParam) {
		// 获取当前登录用户
		UmsMember currentMember = memberService.getNewCurrentMember();
		if (null == currentMember) {
			return new CommonResult().failed("请先登录");
		}
		SmsGroup group = groupService.getById(orderParam.getGroupId());
		if (null == group) {
			return new CommonResult().failed("拼团信息有误");
		}
		// 根据科技馆ID查询科技馆详情
		SysStore store = storeService.getById(orderParam.getShopId());
		if (null == store) {
			return new CommonResult().failed("科技馆信息有误");
		}
		// 订单信息
		OmsOrder order = new OmsOrder();
		order.setMemberId(currentMember.getId());
		order.setMemberUsername(currentMember.getNickname());
		order.setPayType(0);// 支付方式：0->未支付
		order.setSourceType(OrderSource.weixinApplet.code());// 订单来源：1->小程序
		order.setOrderSn(generateOrderSn(order));
		order.setTotalAmount(orderParam.getTotalAmount());
		order.setPayAmount(orderParam.getPayAmount());
		order.setFreightAmount(orderParam.getFreightAmount());
		order.setStatus(OrderStatus.INIT.getValue());// 订单状态：0待付款
		order.setGroupId(orderParam.getGroupId());
		order.setOrderType(OrderType.PIN_GROUP.code());// 订单类型：3拼团
		order.setStoreId(orderParam.getShopId());
		order.setStoreName(store.getName());
		order.setNote(orderParam.getContent());
		order.setConfirmStatus(0);// 确认收货状态：0->未确认；1->已确认
		order.setDeleteStatus(0);// 删除状态：0->未删除；1->已删除
		order.setIsComment(1);// 是否评论，1未评论，2已评论
		// 判断是否填写收货地址
		if (ValidatorUtils.notEmpty(orderParam.getAddressId())) {
			UmsMemberReceiveAddress receiveAddress = addressService.getById(orderParam.getAddressId());
			order.setReceiverName(receiveAddress.getName());
			order.setReceiverPhone(receiveAddress.getPhoneNumber());
			order.setReceiverPostCode(receiveAddress.getPostCode());
			order.setReceiverProvince(receiveAddress.getProvince());
			order.setReceiverCity(receiveAddress.getCity());
			order.setReceiverRegion(receiveAddress.getRegion());
			order.setReceiverDetailAddress(receiveAddress.getDetailAddress());
		}

		SmsCouponHistory couponHistory = new SmsCouponHistory();
		// 判断是否使用优惠券
		if (ValidatorUtils.notEmpty(orderParam.getCouponId())) {
			// 根据优惠券ID查询优惠券详情
			SmsCoupon coupon = couponService.getById(orderParam.getCouponId());
			order.setCouponId(orderParam.getCouponId());
			order.setCouponAmount(coupon.getAmount());
		} else {
			order.setCouponAmount(BigDecimal.ZERO);
		}

		OmsOrderSetting orderSetting = orderSettingMapper.selectById(1);
		order.setAutoConfirmDay(orderSetting.getConfirmOvertime());
		order.setCreateTime(new Date());
		// 根据商品ID查询商品详情
		PmsProduct product = productService.getById(orderParam.getGoodsId());
		if (null != product) {
			order.setGoodsId(product.getId());
			order.setGoodsName(product.getName());
			// 生成订单
			orderService.save(order);
			if (ValidatorUtils.notEmpty(orderParam.getCouponId())) {
				// 更新优惠券使用状态
				couponHistory.setId(orderParam.getCouponId());
				couponHistory.setUseStatus(1);
				couponHistory.setUseTime(new Date());
				couponHistory.setOrderId(order.getId());
				couponHistory.setOrderSn(order.getOrderSn());
				couponHistoryService.updateById(couponHistory);
			}
			// 声明订单商品清单实体类
			OmsOrderItem orderItem = new OmsOrderItem();
			orderItem.setActId(orderParam.getGroupId());
			orderItem.setActEndTime(group.getEndTime());
			orderItem.setOrderId(order.getId());
			orderItem.setOrderSn(order.getOrderSn());
			orderItem.setProductId(product.getId());
			orderItem.setProductPic(product.getPic());
			orderItem.setProductName(product.getName());
			orderItem.setProductSubTitle(product.getSubTitle());
			orderItem.setProductBrand(product.getBrandName());
			orderItem.setProductSn(product.getProductSn());
			orderItem.setProductQuantity(orderParam.getTotal());
			orderItem.setProductCategoryId(product.getProductCategoryId());
			// 根据库存ID查询商品库存
			PmsSkuStock skuStock = skuStockService.getById(orderParam.getSkuId());
			if (null != skuStock) {
				orderItem.setProductAttr(skuStock.getMeno());
				orderItem.setSp1(skuStock.getSp1());
				orderItem.setSp2(skuStock.getSp2());
				orderItem.setSp3(skuStock.getSp3());
				orderItem.setSp4(skuStock.getSp4());
				orderItem.setSp5(skuStock.getSp5());
				orderItem.setSp6(skuStock.getSp6());
				orderItem.setProductPrice(group.getGroupPrice());
				orderItem.setProductSkuId(skuStock.getId());
				orderItem.setProductSkuCode(skuStock.getSkuCode());
				// 判断商品库存是否充足
				if (skuStock.getStock() >= orderParam.getTotal()) {
					skuStock.setStock(skuStock.getStock() - orderParam.getTotal());
				} else {
					return new CommonResult().failed("库存不足");
				}
				// 核减库存数量
				skuStockService.updateById(skuStock);
			} else { // 无商品库存，直接对商品数量进行核减
				orderItem.setProductPrice(group.getGroupPrice());
				product.setStock(product.getStock() - orderParam.getTotal());
				productService.updateById(product);
			}
			orderItem.setRealAmount(orderParam.getPayAmount());
			orderItem.setStoreId(orderParam.getShopId());
			orderItem.setStoreName(product.getStoreName());
			orderItem.setStatus(OrderStatus.INIT.getValue());
			orderItem.setType(product.getProductType());
			orderItem.setIsFenxiao(product.getIsFenxiao());
			if (ValidatorUtils.notEmpty(orderParam.getInviteMemberId())) {
				orderItem.setInviteMemberId(orderParam.getInviteMemberId());
			}
			orderItem.setIsComment(0);
			// 生成订单商品清单
			orderItemService.save(orderItem);
		}

		OmsOrderOperateHistory history = new OmsOrderOperateHistory();
		history.setOrderId(order.getId());
		history.setCreateTime(new Date());
		history.setOperateMan(currentMember.getNickname());
		history.setPreStatus(-1);
		history.setOrderStatus(OrderStatus.INIT.getValue());
		history.setNote("创建订单");
		orderOperateHistoryService.save(history);

		if (orderParam.getGroupType() == 1) {// 发起拼团
			// 拼团信息SmsGroupRecord
			SmsGroupRecord groupRecord = new SmsGroupRecord();
			groupRecord.setGroupId(orderParam.getGroupId());
			groupRecord.setStatus("1");// 状态 1>>初始状态 2拼团成功
			groupRecord.setCreateTime(new Date());
			groupRecord.setStoreId(store.getId());
			groupRecord.setHandleStatus(1);// TODO 状态 1>>初始状态 2定时任务，将订单状态已更新
			groupRecordMapper.insert(groupRecord);
			// 拼团信息SmsGroupMember
			SmsGroupMember groupMember = new SmsGroupMember();
			groupMember.setGoodsId(orderParam.getGoodsId());
			groupMember.setName(currentMember.getNickname());
			groupMember.setMemberId(currentMember.getId());
			groupMember.setPic(currentMember.getIcon());
			groupMember.setStatus(1);// 状态 1>>初始状态 2支付成功
			groupMember.setOrderId(order.getId());
			groupMember.setCreateTime(new Date());
//			groupMember
//					.setExipreTime((flashOrderOvertime - diff) > 0 ? group.getEndTime().getTime() : flashOrderOvertime);// 有效支付时间
			groupMember.setExipreTime(orderSetting.getFlashOrderOvertime().longValue());// 有效支付时间
			groupMember.setGroupRecordId(groupRecord.getId());
			groupMember.setGroupId(groupRecord.getGroupId());
			groupMember.setStoreId(store.getId());
			groupMemberMapper.insert(groupMember);
		} else if (orderParam.getGroupType() == 2) {// 参与拼团
			List<SmsGroupMember> list1 = groupMemberMapper
					.selectList(new QueryWrapper<SmsGroupMember>().eq("group_record_id", orderParam.getMgId()));
			if (list1 != null && list1.size() > group.getMaxPeople()) {
				return new CommonResult().failed("此拼团已达最大人数");
			}
			for (SmsGroupMember smsGroupMember : list1) {
				if (smsGroupMember.getMemberId().equals(currentMember.getId())) {
					return new CommonResult().failed("你已经参加过此团");
				}
			}
			SmsGroupMember groupMember = new SmsGroupMember();
			groupMember.setGoodsId(orderParam.getGoodsId());
			groupMember.setName(currentMember.getNickname());
			groupMember.setMemberId(currentMember.getId());
			groupMember.setPic(currentMember.getIcon());
			groupMember.setStatus(1);// 未支付
			groupMember.setOrderId(order.getId());
			groupMember.setCreateTime(new Date());
//			long flashOrderOvertime = orderSetting.getFlashOrderOvertime().longValue();
//			long diff = group.getEndTime().getTime() - new Date().getTime();
//			groupMember
//					.setExipreTime((flashOrderOvertime - diff) > 0 ? group.getEndTime().getTime() : flashOrderOvertime);// 有效支付时间
			groupMember.setExipreTime(orderSetting.getFlashOrderOvertime().longValue());// 有效支付时间
			groupMember.setGroupRecordId(orderParam.getMgId());
			groupMember.setGroupId(orderParam.getGroupId());
			groupMemberMapper.insert(groupMember);
		}
		Map<String, Object> result = new HashMap<>();
		result.put("order", order);
		return new CommonResult().success("下单成功", result);
	}

	@Transactional
	@Override
	public Object submitFlashPromotionOrder(OrderParam orderParam) {
		// 获取当前登录用户
		UmsMember currentMember = memberService.getNewCurrentMember();
		if (null == currentMember) {
			return new CommonResult().failed("请先登录");
		}
		SmsFlashPromotionProductRelation flashPromotionProductRelation = flashPromotionProductRelationService
				.getById(orderParam.getSkillId());
		if (null == flashPromotionProductRelation) {
			return new CommonResult().failed("秒杀商品信息有误");
		}
		// 根据科技馆ID查询科技馆详情
		SysStore store = storeService.getById(orderParam.getShopId());
		if (null == store) {
			return new CommonResult().failed("科技馆信息有误");
		}
		if (flashPromotionProductRelation.getFlashPromotionCount() < orderParam.getTotal()) {
			return new CommonResult().failed("秒杀商品库存不足");
		}
		boolean flashPromotionLimitFlag = judgeFlashPromotionLimit(currentMember.getId(),
				flashPromotionProductRelation.getId(), orderParam.getTotal());
		if (!flashPromotionLimitFlag) {
			return new CommonResult().failed("秒杀商品已限购");
		}
		// 订单信息
		OmsOrder order = new OmsOrder();
		order.setMemberId(currentMember.getId());
		order.setMemberUsername(currentMember.getNickname());
		order.setPayType(0);// 支付方式：0->未支付；1->支付宝；2->微信；3->余额支付；4->积分兑换
		order.setSourceType(OrderSource.weixinApplet.code());// 订单来源：1->小程序
		order.setOrderSn(generateOrderSn(order));
		order.setTotalAmount(orderParam.getTotalAmount());
		order.setPayAmount(orderParam.getPayAmount());
		order.setFreightAmount(orderParam.getFreightAmount());
		order.setStatus(OrderStatus.INIT.getValue());// 订单状态：0->待付款
		order.setOrderType(OrderType.SKILL.code());// 订单类型：2->秒杀订单
		order.setStoreId(store.getId());
		order.setStoreName(store.getName());
		order.setNote(orderParam.getContent());
		order.setConfirmStatus(0);// 确认收货状态：0->未确认；1->已确认
		order.setDeleteStatus(0);// 删除状态：0->未删除；1->已删除
		order.setIsComment(1);//// 是否评论，1未评论，2已评论

		// 判断是否填写收货地址
		if (ValidatorUtils.notEmpty(orderParam.getAddressId())) {
			UmsMemberReceiveAddress receiveAddress = addressService.getById(orderParam.getAddressId());
			order.setReceiverName(receiveAddress.getName());
			order.setReceiverPhone(receiveAddress.getPhoneNumber());
			order.setReceiverPostCode(receiveAddress.getPostCode());
			order.setReceiverProvince(receiveAddress.getProvince());
			order.setReceiverCity(receiveAddress.getCity());
			order.setReceiverRegion(receiveAddress.getRegion());
			order.setReceiverDetailAddress(receiveAddress.getDetailAddress());
		}

		SmsCouponHistory couponHistory = new SmsCouponHistory();
		// 判断是否使用优惠券
		if (ValidatorUtils.notEmpty(orderParam.getCouponId())) {
			// 根据优惠券ID查询优惠券详情
			SmsCoupon coupon = couponService.getById(orderParam.getCouponId());
			order.setCouponId(orderParam.getCouponId());
			order.setCouponAmount(coupon.getAmount());
		} else {
			order.setCouponAmount(BigDecimal.ZERO);
		}

		// 查询订单自动确认时间
		OmsOrderSetting orderSetting = orderSettingMapper.selectById(1);
		order.setAutoConfirmDay(orderSetting.getConfirmOvertime());
		order.setCreateTime(new Date());

		// 根据商品ID查询商品详情
		PmsProduct product = productService.getById(orderParam.getGoodsId());
		if (null != product) {
			order.setGoodsId(product.getId());
			order.setGoodsName(product.getName());
			// 生成订单
			orderService.save(order);

			if (ValidatorUtils.notEmpty(orderParam.getCouponId())) {
				// 更新优惠券使用状态
				couponHistory.setId(orderParam.getCouponId());
				couponHistory.setUseStatus(1);
				couponHistory.setUseTime(new Date());
				couponHistory.setOrderId(order.getId());
				couponHistory.setOrderSn(order.getOrderSn());
				couponHistoryService.updateById(couponHistory);
			}

			// 声明订单商品清单实体类
			OmsOrderItem orderItem = new OmsOrderItem();
			orderItem.setActId(orderParam.getSkillId());
			SmsFlashPromotion flashPromotion = flashPromotionService
					.getById(flashPromotionProductRelation.getFlashPromotionId());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String endDate = sdf.format(flashPromotion.getEndDate());
			SmsFlashPromotionSession flashPromotionSession = flashPromotionSessionService
					.getById(flashPromotionProductRelation.getFlashPromotionSessionId());
			sdf = new SimpleDateFormat("HH:mm:ss");
			String endTime = sdf.format(flashPromotionSession.getEndTime());
			sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				orderItem.setActEndTime(sdf.parse(endDate + " " + endTime));
			} catch (ParseException e) {
				return new CommonResult().failed("秒杀时间有误");
			}
			orderItem.setOrderId(order.getId());
			orderItem.setOrderSn(order.getOrderSn());
			orderItem.setProductId(product.getId());
			orderItem.setProductPic(product.getPic());
			orderItem.setProductName(product.getName());
			orderItem.setProductSubTitle(product.getSubTitle());
			orderItem.setProductBrand(product.getBrandName());
			orderItem.setProductSn(product.getProductSn());
			orderItem.setProductQuantity(orderParam.getTotal());
			orderItem.setProductCategoryId(product.getProductCategoryId());
			// 根据库存ID查询商品库存
			PmsSkuStock skuStock = skuStockService.getById(orderParam.getSkuId());
			if (null != skuStock) {
				orderItem.setProductAttr(skuStock.getMeno());
				orderItem.setSp1(skuStock.getSp1());
				orderItem.setSp2(skuStock.getSp2());
				orderItem.setSp3(skuStock.getSp3());
				orderItem.setSp4(skuStock.getSp4());
				orderItem.setSp5(skuStock.getSp5());
				orderItem.setSp6(skuStock.getSp6());
				orderItem.setProductPrice(flashPromotionProductRelation.getFlashPromotionPrice());
				orderItem.setProductSkuId(skuStock.getId());
				orderItem.setProductSkuCode(skuStock.getSkuCode());
				// 判断商品库存是否充足
				if (skuStock.getStock() >= orderParam.getTotal()) {
					skuStock.setStock(skuStock.getStock() - orderParam.getTotal());
				} else {
					return new CommonResult().failed("库存不足");
				}
				// 核减库存数量
				skuStockService.updateById(skuStock);
			} else { // 无商品库存，直接对商品数量进行核减
				orderItem.setProductPrice(flashPromotionProductRelation.getFlashPromotionPrice());
				product.setStock(product.getStock() - orderParam.getTotal());
				productService.updateById(product);
			}
			// 秒杀库存
			flashPromotionProductRelation.setFlashPromotionCount(
					flashPromotionProductRelation.getFlashPromotionCount() - orderParam.getTotal());
			flashPromotionProductRelationService.updateById(flashPromotionProductRelation);

			orderItem.setRealAmount(orderParam.getPayAmount());
			orderItem.setStoreId(store.getId());
			orderItem.setStoreName(store.getName());
			orderItem.setStatus(OrderStatus.INIT.getValue());
			orderItem.setType(product.getProductType());
			orderItem.setIsFenxiao(product.getIsFenxiao());
			if (ValidatorUtils.notEmpty(orderParam.getInviteMemberId())) {
				orderItem.setInviteMemberId(orderParam.getInviteMemberId());
			}
			orderItem.setIsComment(0);
			// 生成订单商品清单
			orderItemService.save(orderItem);
		}

		OmsOrderOperateHistory history = new OmsOrderOperateHistory();
		history.setOrderId(order.getId());
		history.setCreateTime(new Date());
		history.setOperateMan(currentMember.getNickname());
		history.setPreStatus(-1);
		history.setOrderStatus(OrderStatus.INIT.getValue());
		history.setNote("创建订单");
		orderOperateHistoryService.save(history);

		Map<String, Object> result = new HashMap<>();
		result.put("order", order);
		return new CommonResult().success("下单成功", result);
	}

	/**
	 * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
	 */
	private String generateOrderSn(OmsOrder order) {
		StringBuilder sb = new StringBuilder();
		sb.append(System.currentTimeMillis());
		sb.append(String.format("%02d", order.getSourceType()));
		sb.append(String.format("%02d", order.getPayType()));
		sb.append(order.getMemberId());
		return sb.toString();
	}

	/**
	 * 每人秒杀限购数量判断
	 * 
	 * @param memberId
	 * @param productId
	 * @param flashPromotionProductRelationId
	 * @param total
	 * @return true：可购买
	 */
	@Override
	public boolean judgeFlashPromotionLimit(Long memberId, Long flashPromotionProductRelationId, Integer total) {
		SmsFlashPromotionProductRelation flashPromotionProductRelation = flashPromotionProductRelationService
				.getById(flashPromotionProductRelationId);
		int count = orderItemService.countProductQuantity(memberId, OrderType.SKILL.code(),
				flashPromotionProductRelation.getId());
		if (flashPromotionProductRelation.getFlashPromotionLimit() >= count + total) {
			return true;
		}
		return false;
	}

}
